package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.service.SetmealService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    private final DishFlavorService dishFlavorService;

    private final SetmealDishService setmealDishService;

    private final DishMapper dishMapper;


    /**
     * 新增菜品
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO,dish);

        //向菜品表插入1条数据
        save(dish);

        //dish的id自增长 获取insert语句生成的主键值  去数据库获取该数据
        Dish dishMysql = query().eq("name", dish.getName()).one();
        //数据库dish的id值
        Long dishId = dishMysql.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() >0){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
                //向口味表插入n条数据
                dishFlavorService.save(flavor);
            }
        }
    }


    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        String name = dishPageQueryDTO.getName();
        Integer categoryId = dishPageQueryDTO.getCategoryId();
        Integer status = dishPageQueryDTO.getStatus();
        //分页条件
        Page<Dish> pageCondition = Page.of(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
//        //排序条件
//        pageCondition.addOrder(new OrderItem("price",true))
//                .addOrder(new OrderItem("create_time",false));
        //分页查询 select d.* , c.name as categoryName from dish d left outer join categoryId c on d.categoryId =c.id where name = ? and categoryId = ? and status =?
        IPage<DishVO> page = dishMapper.selectJoinPage(new Page<>(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize()), DishVO.class,
                new MPJLambdaWrapper<DishVO>()
                        .selectAll(Dish.class) // 选择Dish的所有字段
                        .selectAs(Category::getName, DishVO::getCategoryName) // 选择Category的name字段 as categoryName
                        .leftJoin(Category.class, Category::getId, Dish::getCategoryId) // 左连接Category表
                        .eq(name!=null, Dish::getName, name)
                        .eq(categoryId!=null, Dish::getCategoryId,categoryId)
                        .eq(status!=null, Dish::getStatus,status)
                        .orderByDesc(Dish::getCreateTime)
        );

        return new PageResult(page.getTotal(), page.getRecords());
    }


    /**
     * 根据id查询菜品和对应的口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据id查询菜品数据
        Dish dish = getById(id);

        //根据菜品查询口味数据
        List<DishFlavor> dishFlavorList = dishFlavorService.lambdaQuery().eq(DishFlavor::getDishId, dish.getId()).list();
        //将查询到的数据封装到vo
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavorList);

        return dishVO;
    }


    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {

        //根据菜品查询口味数据
        List<DishFlavor> dishFlavorList = dishFlavorService.lambdaQuery().eq(DishFlavor::getDishId, dishDTO.getId()).list();
        for (DishFlavor dishFlavor : dishFlavorList) {
            //删除口味
            dishFlavorService.removeById(dishFlavor);
        }

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品
        updateById(dish);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() >0){
            for (DishFlavor flavor : flavors) {
                //不需要，dish_id没有变
//                flavor.setDishId(dishDTO.getId());
                //向口味表插入n条数据
                dishFlavorService.save(flavor);
            }
        }


    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder().id(id).status(status).build();
        updateById(dish);
    }


//    /**
//     * 菜品批量删除
//     * @param ids
//     * @return
//     */
//    public void deleteBatch(List<Long> ids) {
//
//        List<SetmealDish> setmealDishList = new ArrayList<>();
//
//        for (Long id : ids) {
//            Dish dish = query().eq("id", id).one();
//            //判断当前菜品是否能删除--是否存在起售中的菜品？
//            if(dish.getStatus() == StatusConstant.ENABLE){
//                //当前菜品处于起售中,不能删除
//                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
//            }
//            SetmealDish setmealDish = setmealDishService.query().eq("id", id).one();
//            //下面用不了，我要返回一个对象
////            setmealDishService.lambdaQuery().eq(SetmealDish::getDishId, id)
//            setmealDishList.add(setmealDish);
//        }
//
//        //下面用不了 ids的参数不能是列表对象
////        List<SetmealDish> id = setmealDishService.query().eq("id", ids).list();
//
//        //判断当前菜品是否能删除--是否被套餐关联？
//        if (setmealDishList != null && setmealDishList.size() > 0){
//            //当前菜品被套餐关联了,不能删除
//            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
//        }
//        //删除菜品表中的菜品数据
//
//        //删除菜品关联的口味数据
//
//    }
}
